package mymongo

import (
	"mygo/mystruct"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

/* =================================================================================
   视频弹幕操作
*/
func (api Collections) Danmaku_Get(id string) (*mystruct.Retdate, *mystruct.Barrage_All) {
	results := &mystruct.Retdate{"danmaku-get", mystruct.MyCodeOk, "succeed"}

	var result mystruct.Barrage_All
	err := api.FindOne(context.TODO(), bson.D{{"id", id}}).Decode(&result)
	if err != nil {
		results.Mesg = err.Error()
	 	results.Code = mystruct.MyCodeErr
	 	return results, nil
	}
	return results, &result
}

func (api Collections) Danmaku_Add(outult *mystruct.Barrage_All) *mystruct.Retdate {
	results := &mystruct.Retdate{"danmaku-add", mystruct.MyCodeOk, "succeed"}

	_, err := api.InsertOne(context.TODO(), outult)
	if err != nil {
	 	results.Mesg = err.Error()
	 	results.Code = mystruct.MyCodeErr
	}
	return results
}

func (api Collections) Danmaku_Push(outult *mystruct.Barrage_One) *mystruct.Retdate {
	results := &mystruct.Retdate{"danmaku-push", mystruct.MyCodeOk, "succeed"}
	filter := bson.M{"id": outult.Id}
	update := bson.M{"$push": bson.M{"data": []interface{}{outult.Time, outult.Type, outult.Color, outult.Author, outult.Text}}}
	opts := options.Update().SetUpsert(true)
	_, err := api.UpdateOne(context.TODO(), filter, update, opts)
	if err != nil {
	 	results.Mesg = err.Error()
	 	results.Code = mystruct.MyCodeErr
	}
	return results
}

func (api Collections) Danmaku_Del(id string) *mystruct.Retdate {
	results := &mystruct.Retdate{"danmaku-del", mystruct.MyCodeOk, "succeed"}

	ret, err := api.DeleteOne(context.TODO(), bson.M{"id": id})
	results.Code = ret.DeletedCount
	if err != nil{
		results.Mesg = err.Error()
		results.Code = mystruct.MyCodeErr
	}
	return results
}